/*
 * Copyright 2015-2102 Fast(http://www.cloudate.net) Group.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fast.pay.controller;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fast.pay.common.core.enums.PayWayEnum;
import com.fast.pay.common.core.enums.PublicEnum;
import com.fast.pay.common.core.utils.StringUtil;
import com.fast.pay.trade.service.RpTradePaymentManagerService;
import com.fast.pay.trade.vo.OrderPayResultVo;
import com.fast.remote.channel.api.ChannelPayApi;
import com.fast.remote.channel.vo.NoticeCfgVo;
import com.fast.remote.channel.vo.NoticeParamType;

@Controller
@RequestMapping(value = "/scanPayNotify")
public class ScanPayNotifyController {
	
    private static final Logger logger = LoggerFactory.getLogger(ScanPayNotifyController.class);

    @Autowired
    private RpTradePaymentManagerService rpTradePaymentManagerService;


    @RequestMapping("/result/{channelCode}/{id}")
    @ResponseBody
    public String result(@PathVariable("channelCode") String channelCode,@PathVariable("id") String id, HttpServletRequest httpServletRequest ) throws Exception {
    	try {
    		String ioParam = "";
        	Map<String ,String> resultMap = new HashMap<>();
        	//获得对应的通道配置
        	ChannelPayApi bean = rpTradePaymentManagerService.getChennelBean(channelCode);
        	NoticeCfgVo cfg = bean.syncNoticeCfg();
        	String encode = cfg.getEncoding();
        	if(StringUtil.isEmpty(encode)) encode = "utf-8";
        	httpServletRequest.setCharacterEncoding(encode);
        	
        	if(NoticeParamType.IOSTRING.equals(cfg.getParamtype()) ) {
        		InputStream in =httpServletRequest.getInputStream();
        		byte[] bytes = new byte[0];
        		bytes = new byte[in.available()];
        		in.read(bytes);
        		ioParam = new String(bytes,encode);
        	}else {
        		 Map requestParams = httpServletRequest.getParameterMap();
    	         for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
    	            String name = (String) iter.next();
    	            String[] values = (String[]) requestParams.get(name);
    	            if(values.length>0)resultMap.put(name, values[0]);
    	        }
        	}
            OrderPayResultVo scanPayByResult = rpTradePaymentManagerService.completeScanPayByResult(channelCode, id,resultMap,ioParam,bean);
            if(PublicEnum.YES.toString().equals(scanPayByResult.getStatus())) {
            	return cfg.getBackMsg();
            }
		} catch (Exception e) {
			logger.error("异步通知出现异常："+id+";"+channelCode,e);
		}
        return "ERROR";
    }

}
